package net.kansun.poc;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingDeque;

/**
 * This is a demo of the classical multithreading issue, the consumer-producer pattern.
 */
public class ConsumerProducerDemoUsingBlockingQueue {

   public static void main(String[] args) {

      BlockingQueue<String> resources = new LinkedBlockingDeque<String>();

      Thread consumerThread = new Thread(new Consumer(resources), "Customer");
      Thread producerThread = new Thread(new Producer(resources), "Producer");

      consumerThread.start();
      producerThread.start();
   }

   static class Consumer implements Runnable {

      private final BlockingQueue<String> resources;

      public Consumer(BlockingQueue<String> resources) {
         this.resources = resources;
      }

      @Override
      public void run() {

         while (true) {

            try {
               String s = resources.take();
               System.out.println(Thread.currentThread().getName() + ": consumed resource " + s);
               Thread.sleep(50);
            } catch (InterruptedException e) {
            }

         }

      }
   }

   static class Producer implements Runnable {

      private final BlockingQueue<String> resources;

      public Producer(BlockingQueue<String> resources) {

         this.resources = resources;
      }

      @Override
      public void run() {

         while (true) {
            try {
               String s = String.valueOf(System.currentTimeMillis());
               resources.put(s);
               System.out.println(Thread.currentThread().getName() + ": produced resource " + s);
               Thread.sleep(50);
            } catch (InterruptedException e) {
            }
         }

      }
   }
}
